package cn.lg.soar.mvc.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.time.Duration;
import java.util.List;

/**
 * 跨域配置
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@RefreshScope
@Configuration
@ConditionalOnProperty(name = "lg.cors.enabled", havingValue = "true")
public class CorsConfigurer {

    @Value("${lg.cors.mappings:/**}")
    private List<String> mappings;

    @Value("${lg.cors.origins:*}")
    private List<String> origins;

    @Value("${lg.cors.headers:*}")
    private List<String> headers;

    @Value("${lg.cors.methods:*}")
    private List<String> methods;

    @Value("${lg.cors.age:3600s}")
    private Duration age;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //允许的域名
        corsConfiguration.setAllowedOrigins(origins);
        //允许的头
        corsConfiguration.setAllowedHeaders(headers);
        //允许的方法
        corsConfiguration.setAllowedMethods(methods);
        //有效期
        corsConfiguration.setMaxAge(age);

        for(String mapping: mappings){
            source.registerCorsConfiguration(mapping, corsConfiguration);
        }
        return new CorsFilter(source);
    }
}
